package com.chaos.eurekaproducer.service;

import com.alibaba.fastjson.JSON;
import com.chaos.eurekaproducer.domain.User;
import com.chaos.eurekaproducer.mapper.UserMapper;
import com.chaos.eurekaproducer.rabbitmq.RabbitMqProductor;
import com.rabbitmq.tools.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.List;

/**
 * @author liaopeng
 * @title: UserServiceImpl
 * @projectName eureka-producer
 * @description: TODO
 * @date 2021/5/14下午6:07
 */
@Service
public class UserServiceImpl implements IUserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RabbitMqProductor rabbitMqProductor;

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,rollbackFor = Exception.class)
    public Integer insert(User user) {
        int insert=0;
        try {
            insert= userMapper.insert(user);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("最后执行finally");
        }
        return insert;
    }

    @Override
    public int batchInsert(List<User> users) {
        return userMapper.batchInsert(users);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,rollbackFor = Exception.class)
    public int update(User user) {
        int n=0;
        try {
            n = userMapper.updateById(user);
            rabbitMqProductor.sendAfterTransaction("chaos.exchange","chaos.routing.key1111",JSON.toJSONString(user));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("最后执行finally");
        }
        System.out.println("return前执行");
        return n;
    }

    @Override
    public User selectById(User user) {
        return userMapper.selectById(user);
    }
}
